import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 前台操作面板
 */
public class FrontDeskPanel extends JPanel {
    private JTable checkInTable;
    private DefaultTableModel tableModel;
    private JTextField searchField;

    public FrontDeskPanel() {
        setupUI();
        refreshData();
    }

    private void setupUI() {
        setLayout(new BorderLayout());
        setBackground(Color.WHITE);
        setBorder(new EmptyBorder(20, 20, 20, 20));

        // 标题和操作面板
        JPanel topPanel = createTopPanel();
        add(topPanel, BorderLayout.NORTH);

        // 入住信息表格
        JPanel tablePanel = createTablePanel();
        add(tablePanel, BorderLayout.CENTER);
    }

    private JPanel createTopPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(Color.WHITE);
        panel.setBorder(new EmptyBorder(0, 0, 20, 0));

        // 标题
        JLabel titleLabel = new JLabel("前台操作");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        titleLabel.setForeground(HotelManagementSystem.getPrimaryColor());
        panel.add(titleLabel, BorderLayout.WEST);

        // 操作按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.setBackground(Color.WHITE);

        JButton checkInButton = createStyledButton("开放登记", HotelManagementSystem.getSuccessColor());
        checkInButton.addActionListener(e -> showCheckInDialog());
        buttonPanel.add(checkInButton);

        JButton checkOutButton = createStyledButton("结账", HotelManagementSystem.getAccentColor());
        checkOutButton.addActionListener(e -> checkOutGuest());
        buttonPanel.add(checkOutButton);

        JButton extendButton = createStyledButton("续住", HotelManagementSystem.getSecondaryColor());
        extendButton.addActionListener(e -> extendStay());
        buttonPanel.add(extendButton);

        JButton refreshButton = createStyledButton("刷新", new Color(108, 117, 125));
        refreshButton.addActionListener(e -> refreshData());
        buttonPanel.add(refreshButton);

        panel.add(buttonPanel, BorderLayout.EAST);

        // 搜索面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        searchPanel.setBackground(Color.WHITE);

        JLabel searchLabel = new JLabel("搜索客人:");
        searchLabel.setFont(HotelManagementSystem.getButtonFont());
        searchPanel.add(searchLabel);

        searchField = new JTextField(15);
        searchField.setFont(HotelManagementSystem.getButtonFont());
        searchPanel.add(searchField);

        JButton searchButton = createStyledButton("搜索", HotelManagementSystem.getPrimaryColor());
        searchButton.addActionListener(e -> searchGuest());
        searchPanel.add(searchButton);

        panel.add(searchPanel, BorderLayout.SOUTH);

        return panel;
    }

    private JPanel createTablePanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(Color.WHITE);

        // 表格标题
        JLabel tableTitle = new JLabel("当前入住信息");
        tableTitle.setFont(new Font("微软雅黑", Font.BOLD, 16));
        tableTitle.setForeground(HotelManagementSystem.getPrimaryColor());
        tableTitle.setBorder(new EmptyBorder(0, 0, 10, 0));
        panel.add(tableTitle, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = { "客人ID", "姓名", "房间号", "入住日期", "预计退房日期", "总金额", "状态" };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        checkInTable = new JTable(tableModel);
        checkInTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        checkInTable.setRowHeight(30);
        checkInTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        checkInTable.getTableHeader().setBackground(HotelManagementSystem.getBackgroundColor());
        checkInTable.setSelectionBackground(HotelManagementSystem.getSecondaryColor().brighter());

        JScrollPane scrollPane = new JScrollPane(checkInTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private JButton createStyledButton(String text, Color backgroundColor) {
        JButton button = new JButton(text);
        button.setFont(HotelManagementSystem.getButtonFont());
        button.setBackground(backgroundColor);
        button.setForeground(Color.WHITE);
        button.setBorder(new EmptyBorder(8, 15, 8, 15));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 添加鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(backgroundColor.darker());
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(backgroundColor);
            }
        });

        return button;
    }

    private void showCheckInDialog() {
        CheckInDialog dialog = new CheckInDialog((JFrame) SwingUtilities.getWindowAncestor(this));
        dialog.setVisible(true);
        if (dialog.isConfirmed()) {
            refreshData();
        }
    }

    private void checkOutGuest() {
        int selectedRow = checkInTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要结账的客人！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String guestId = (String) tableModel.getValueAt(selectedRow, 0);
        String guestName = (String) tableModel.getValueAt(selectedRow, 1);
        String roomNumber = (String) tableModel.getValueAt(selectedRow, 2);

        int result = JOptionPane.showConfirmDialog(this,
                "确定要为客人 " + guestName + " (房间" + roomNumber + ") 办理结账吗？",
                "确认结账", JOptionPane.YES_NO_OPTION);

        if (result == JOptionPane.YES_OPTION) {
            // 获取入住记录
            List<CheckIn> checkIns = DataManager.getInstance().getAllCheckIns();
            CheckIn checkInRecord = null;
            for (CheckIn checkIn : checkIns) {
                if (checkIn.getGuestId().equals(guestId)) {
                    checkInRecord = checkIn;
                    break;
                }
            }

            if (checkInRecord != null) {
                // 设置实际退房日期
                checkInRecord.setCheckOutDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                checkInRecord.setStatus("已结账");

                // 添加到历史记录
                DataManager.getInstance().addHistory(checkInRecord);

                // 从入住记录中删除
                DataManager.getInstance().removeCheckIn(guestId);

                // 更新房间状态为空闲
                DataManager.getInstance().updateRoomStatus(roomNumber, "空闲");

                JOptionPane.showMessageDialog(this, "结账成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                refreshData();
            }
        }
    }

    private void extendStay() {
        int selectedRow = checkInTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要续住的客人！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String guestId = (String) tableModel.getValueAt(selectedRow, 0);
        String guestName = (String) tableModel.getValueAt(selectedRow, 1);

        String daysStr = JOptionPane.showInputDialog(this, "请输入续住天数:", "续住", JOptionPane.QUESTION_MESSAGE);
        if (daysStr != null && !daysStr.trim().isEmpty()) {
            try {
                int days = Integer.parseInt(daysStr.trim());
                if (days > 0) {
                    // 这里可以实现续住逻辑
                    JOptionPane.showMessageDialog(this, "续住 " + days + " 天成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    refreshData();
                } else {
                    JOptionPane.showMessageDialog(this, "续住天数必须大于0！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(this, "请输入有效的天数！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void searchGuest() {
        String keyword = searchField.getText().trim();
        if (keyword.isEmpty()) {
            refreshData();
            return;
        }

        List<CheckIn> allCheckIns = DataManager.getInstance().getAllCheckIns();
        tableModel.setRowCount(0);

        for (CheckIn checkIn : allCheckIns) {
            if (checkIn.getGuestName().contains(keyword) ||
                    checkIn.getGuestId().contains(keyword) ||
                    checkIn.getRoomNumber().contains(keyword)) {
                Object[] rowData = {
                        checkIn.getGuestId(),
                        checkIn.getGuestName(),
                        checkIn.getRoomNumber(),
                        checkIn.getCheckInDate(),
                        checkIn.getCheckOutDate(),
                        "¥" + checkIn.getTotalAmount(),
                        checkIn.getStatus()
                };
                tableModel.addRow(rowData);
            }
        }
    }

    public void refreshData() {
        List<CheckIn> checkIns = DataManager.getInstance().getAllCheckIns();

        // 清空表格
        tableModel.setRowCount(0);

        // 填充表格数据
        for (CheckIn checkIn : checkIns) {
            Object[] rowData = {
                    checkIn.getGuestId(),
                    checkIn.getGuestName(),
                    checkIn.getRoomNumber(),
                    checkIn.getCheckInDate(),
                    checkIn.getCheckOutDate(),
                    "¥" + checkIn.getTotalAmount(),
                    checkIn.getStatus()
            };
            tableModel.addRow(rowData);
        }

        // 清空搜索框
        searchField.setText("");
    }
}